-module(tdmaclient).
-export([start/1]).
-import(werkzeug, [to_String/1]).


%%Rückgabewert ist eine PID, an die man kill senden kann, um alle Prozesse zu beenden
start([MCIPString, PortA, IIPString, ClientClassA, InitialTimeDeviationA | Params]) ->
  %{ok, IfList} = inet:getifaddrs(),
  %Opts = proplists:get_value(atom_to_list(IIPString), IfList),
  %InterfaceIP = proplists:get_value(addr, Opts),
	{ok, InterfaceIP} = inet_parse:address(atom_to_list(IIPString)),
	{ok, MultiCastIP} = inet_parse:address(atom_to_list(MCIPString)),
    ClientClass = atom_to_list(ClientClassA),
	{Port, _} = string:to_integer(atom_to_list(PortA)),
	{InitialTimeDeviation,_} = string:to_integer(atom_to_list(InitialTimeDeviationA)),
	DataSource   = spawn(fun() -> datasource:start() end),
    DataSink     = spawn(fun() -> datasink:start() end),
    Synchro      = spawn(fun() -> synchro:start(DataSink, InitialTimeDeviation) end),
    %Sender wird nun als Unterprozess von Slotselector gestartet
    %Sender       = spawn(fun() -> sender:start(DataSource, Synchro, Port, InterfaceIP, MultiCastIP, ClientClass) end),
    SlotSelector = spawn(fun() -> slotselector:start(DataSource, Synchro, Port, InterfaceIP, MultiCastIP, ClientClass) end),
    %Receiver     = 
    spawn(fun() -> receiver:start(DataSource, Synchro, DataSink, SlotSelector, Port, InterfaceIP, MultiCastIP) end),
    DataSink ! lists:concat(["TDMAClient auf Port ", to_String(Port), " mit MultiCastIP ", to_String(MultiCastIP), " und Interface ", to_String(InterfaceIP), " gestartet"]),
    case Params of 
        [Debug | _ ] when Debug == debug ->
            pman:start();
        [NoIO | _ ] when NoIO == noio -> 
            DataSink ! kill;
        _ -> 
            ok
    end.



    


   